<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import request from '@/utils/sj-request'
import { ElMessage, ElMessageBox } from 'element-plus'
import QuestionForm from '@/components/sj/QuestionForm.vue'
import { usetikuUserStore } from '@/stores/sj-user'
import { ROLES, hasFeaturePermission } from '@/utils/permission'
import katex from 'katex'
import 'katex/dist/katex.min.css'

// 获取用户信息
const userStore = usetikuUserStore()
const userInfo = computed(() => userStore.userInfo)

// 检查用户是否有权限执行特定操作
const canEditQuestion = computed(() => {
  // 管理员和学科组长可以编辑试题
  return userInfo.value.roleName === ROLES.ADMIN || userInfo.value.roleName === ROLES.SUBJECT_LEADER
})

const canDeleteQuestion = computed(() => {
  // 管理员和学科组长可以删除试题
  return userInfo.value.roleName === ROLES.ADMIN || userInfo.value.roleName === ROLES.SUBJECT_LEADER
})

// 检查用户是否可以编辑特定试题（基于学科权限）
const canEditSpecificQuestion = (question) => {
  // 管理员可以编辑任何试题
  if (userInfo.value.roleName === ROLES.ADMIN) return true
  
  // 学科组长只能编辑自己学科的试题
  if (userInfo.value.roleName === ROLES.SUBJECT_LEADER) {
    return question.subjectId === userInfo.value.subjectId
  }
  
  // 教师不能编辑试题
  return false
}

// 检查用户是否可以删除特定试题（基于学科权限）
const canDeleteSpecificQuestion = (question) => {
  // 管理员可以删除任何试题
  if (userInfo.value.roleName === ROLES.ADMIN) return true
  
  // 学科组长只能删除自己学科的试题
  if (userInfo.value.roleName === ROLES.SUBJECT_LEADER) {
    return question.subjectId === userInfo.value.subjectId
  }
  
  // 教师不能删除试题
  return false
}

// 试题列表数据
const questionList = ref([])
// 搜索关键词
const searchKeyword = ref('')
// 加载状态
const loading = ref(false)
// 分页参数
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 学科列表
const subjectList = ref([])
// 选中的学科
const selectedSubject = ref('')

// 试题类型列表
const questionTypeList = ref([])
// 选中的试题类型
const selectedType = ref('')

// 知识点列表
const knowledgePointList = ref([])
// 选中的知识点
const selectedKnowledgePoint = ref('')

// 答案类型列表
const answerTypeList = ref([])

// 表单对话框
const dialogVisible = ref(false)
// 编辑模式
const isEdit = ref(false)
// 当前编辑的试题数据
const currentQuestion = ref(null)

// 获取所有学科
const fetchSubjects = async () => {
  try {
    const res = await request({
      url: '/subject/list',
      method: 'get'
    })
    subjectList.value = res.data || []
  } catch (error) {
    console.error('获取学科列表失败:', error)
  }
}

// 获取试题类型列表
const fetchQuestionTypes = async () => {
  try {
    const res = await request({
      url: '/question-type/list',
      method: 'get'
    })
    questionTypeList.value = res.data || []
  } catch (error) {
    console.error('获取试题类型列表失败:', error)
  }
}

// 获取答案类型列表
const fetchAnswerTypes = async () => {
  try {
    const res = await request({
      url: '/answer-type/list',
      method: 'get'
    })
    answerTypeList.value = res.data || []
  } catch (error) {
    console.error('获取答案类型列表失败:', error)
  }
}

// 获取知识点列表

// 获取试题列表
const fetchQuestions = async () => {
  loading.value = true
  try {
    // 构建请求参数
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      keyword: searchKeyword.value,
      questionTypeId: selectedType.value || null,
      knowledgePointId: selectedKnowledgePoint.value || null
    }
    
    // 如果是管理员且选择了学科，则按选择的学科筛选
    if (userInfo.value.roleName === ROLES.ADMIN) {
      if (selectedSubject.value) {
        params.subjectId = selectedSubject.value
      }
    } else {
      // 如果是学科组长或教师，只能查看自己学科的试题
      params.subjectId = userInfo.value.subjectId
    }
    
    const res = await request({
      url: '/question/page',
      method: 'get',
      params: params
    })
    
    if (res.code === 200 && res.data) {
      questionList.value = res.data.records || []
      pagination.value.total = res.data.total || 0
    } else {
      // 如果API未实现，使用模拟数据
      const mockData = {
        total: 25,
        records: [
          { id: 1, name: '以下哪个是JavaScript的基本数据类型?', questionTypeId: 1, hardLevel: 'MEDIUM', subjectName: '前端开发' },
          { id: 2, name: 'Java中的访问修饰符有哪些?', questionTypeId: 2, hardLevel: 'HARD', subjectName: 'Java编程' },
          { id: 3, name: 'HTTP是无状态协议', questionTypeId: 3, hardLevel: 'EASY', subjectName: '计算机网络' },
          { id: 4, name: 'SQL中用于查询数据的语句是____', questionTypeId: 4, hardLevel: 'EASY', subjectName: '数据库' },
          { id: 5, name: '简述MVC设计模式的优点', questionTypeId: 5, hardLevel: 'MEDIUM', subjectName: '软件工程' },
          { id: 6, name: 'React中的状态管理工具有哪些?', questionTypeId: 2, hardLevel: 'MEDIUM', subjectName: '前端开发' },
          { id: 7, name: '线程和进程的区别是什么?', questionTypeId: 5, hardLevel: 'HARD', subjectName: '操作系统' },
          { id: 8, name: 'Python是编译型语言', questionTypeId: 3, hardLevel: 'EASY', subjectName: 'Python编程' },
          { id: 9, name: '冒泡排序的时间复杂度是____', questionTypeId: 4, hardLevel: 'MEDIUM', subjectName: '数据结构' },
          { id: 10, name: '什么是依赖注入?', questionTypeId: 5, hardLevel: 'HARD', subjectName: '软件工程' }
        ]
      }
      
      questionList.value = mockData.records
      pagination.value.total = mockData.total
    }
  } catch (error) {
    console.error('获取试题列表失败:', error)
    ElMessage.error('获取试题列表失败')
  } finally {
    loading.value = false
  }
}

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page
  fetchQuestions()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size
  pagination.value.currentPage = 1
  fetchQuestions()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchQuestions()
}

// 处理重置筛选条件
const handleReset = () => {
  searchKeyword.value = ''
  selectedSubject.value = ''
  selectedType.value = ''
  selectedKnowledgePoint.value = ''
  pagination.value.currentPage = 1
  fetchQuestions()
}

// 处理学科变化
const handleSubjectChange = () => {
  // 清空已选知识点
  selectedKnowledgePoint.value = ''
}

// 打开新增试题对话框
const handleAddQuestion = () => {
  // 检查用户是否有权限添加试题
  if (userInfo.value.roleName === ROLES.TEACHER) {
    ElMessage.warning('您没有权限添加试题')
    return
  }
  
  isEdit.value = false
  currentQuestion.value = null
  dialogVisible.value = true
}

// 打开编辑试题对话框
const handleEditQuestion = async (row) => {
  // 检查用户是否有权限编辑该试题
  if (!canEditSpecificQuestion(row)) {
    ElMessage.warning('您没有权限编辑该试题')
    return
  }
  
  try {
    loading.value = true
    // 获取试题详情
    const res = await request({
      url: `/question/${row.id}`,
      method: 'get'
    })
    
    if (res.code === 200 && res.data) {
      currentQuestion.value = res.data
      isEdit.value = true
      dialogVisible.value = true
    } else {
      // 如果API未实现，使用行数据
      currentQuestion.value = { ...row }
      isEdit.value = true
      dialogVisible.value = true
    }
  } catch (error) {
    console.error('获取试题详情失败:', error)
    ElMessage.error('获取试题详情失败')
  } finally {
    loading.value = false
  }
}

// 处理删除试题
const handleDeleteQuestion = (row) => {
  // 检查用户是否有权限删除该试题
  if (!canDeleteSpecificQuestion(row)) {
    ElMessage.warning('您没有权限删除该试题')
    return
  }
  
  ElMessageBox.confirm(
    '确定要删除这个试题吗？此操作不可逆',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await request({
        url: `/question/${row.id}`,
        method: 'delete'
      })
      
      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchQuestions()
      }
    } catch (error) {
      console.error('删除试题失败:', error)
      ElMessage.error('删除试题失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 当前查看的试题详情数据
const questionDetail = ref(null)
// 试题详情对话框可见性
const questionDetailVisible = ref(false)

// 处理查看试题
const handleViewQuestion = async (row) => {
  try {
    const res = await request({
      url: `/question/${row.id}`,
      method: 'get'
    })
    
    if (res.code === 200 && res.data) {
      // 设置试题详情数据
      questionDetail.value = {
        ...res.data,
        // 处理试题名称中的数学公式
        formattedName: renderMathFormula(res.data.name),
        // 处理试题内容并渲染数学公式
        formattedContent: renderMathFormula(formatQuestionContent(res.data.questionContent)),
        // 格式化难度等级
        difficulty: formatDifficulty(res.data.hardLevel),
        // 获取试题类型名称
        questionTypeName: getQuestionTypeName(res.data.questionTypeId),
        // 获取答案类型名称
        answerTypeName: getAnswerTypeName(res.data.answerTypeId)
      }
      
      // 显示试题详情对话框
      questionDetailVisible.value = true
    }
  } catch (error) {
    console.error('获取试题详情失败:', error)
    ElMessage.error('获取试题详情失败')
  }
}

// 关闭试题详情对话框
const closeQuestionDetail = () => {
  questionDetailVisible.value = false
}

// 处理表单提交成功
const handleFormSuccess = () => {
  dialogVisible.value = false
  fetchQuestions()
}

// 处理表单取消
const handleFormCancel = () => {
  dialogVisible.value = false
}

// 获取试题类型名称
const getQuestionTypeName = (typeId) => {
  const type = questionTypeList.value.find(item => item.id === typeId)
  return type ? type.name : '未知'
}

// 获取答案类型名称
const getAnswerTypeName = (typeId) => {
  const type = answerTypeList.value.find(item => item.id === typeId)
  return type ? type.name : '未知'
}

// 格式化试题类型
const formatQuestionType = (typeId) => {
  return getQuestionTypeName(typeId)
}

// 格式化难度等级
const formatDifficulty = (difficulty) => {
  const difficultyMap = {
    '易': { label: '简单', color: '#67C23A' },
    '中': { label: '中等', color: '#E6A23C' },
    '难': { label: '困难', color: '#F56C6C' }
  }
  return difficultyMap[difficulty] || { label: difficulty, color: '#909399' }
}

// 格式化试题内容
const formatQuestionContent = (content) => {
  if (!content) return ''
  
  try {
    const contentData = JSON.parse(content)
    // 检查是否为键值对对象
    if (typeof contentData === 'object' && !Array.isArray(contentData)) {
      // 将对象转换为选项数组并显示
      return Object.entries(contentData)
        .map(([key, value]) => `${key}. ${value}`)
        .join('  ')
    }
    // 兼容旧格式
    if (contentData.options && Array.isArray(contentData.options)) {
      return contentData.options.map(option => `${option.label}. ${option.content}`).join('  ')
    }
  } catch (e) {
    // 如果解析失败，返回原内容
    return content
  }
  
  return content
}

// 渲染数学公式
const renderMathFormula = (content) => {
  if (!content) return content
  
  try {
    // 解析JSON格式的内容
    let parsedContent = content
    try {
      // 检查是否为JSON字符串
      if (typeof content === 'string' && (content.startsWith('{') || content.startsWith('['))) {
        const contentObj = JSON.parse(content)
        if (typeof contentObj === 'object' && !Array.isArray(contentObj)) {
          // 将对象转换为选项数组并水平排列
          parsedContent = Object.entries(contentObj)
            .map(([key, value]) => {
              // 检查选项内容是否包含公式
              if (typeof value === 'string' && value.includes('$$')) {
                // 先处理选项内容中的公式
                const processedValue = value.replace(/\$\$(.*?)\$\$/g, (match, formula) => {
                  try {
                    return katex.renderToString(formula, {
                      throwOnError: false,
                      displayMode: true,
                      output: 'html'
                    })
                  } catch (e) {
                    console.error('渲染选项公式出错:', e)
                    return match
                  }
                })
                return `${key}. ${processedValue}`
              }
              return `${key}. ${value}`
            })
            .join('  ')
          return parsedContent
        }
      }
    } catch (e) {
      // 如果解析失败，使用原始内容
      console.log('JSON解析失败，使用原始内容:', e)
      parsedContent = content
    }
    
    // 如果内容不包含公式标记，直接返回
    if (!parsedContent.includes('$$')) return parsedContent
    
    // 替换公式
    const regex = /\$\$(.*?)\$\$/g
    return parsedContent.replace(regex, (match, formula) => {
      try {
        return katex.renderToString(formula, {
          throwOnError: false,
          displayMode: false,
          output: 'html'
        })
      } catch (e) {
        console.error('渲染公式出错:', e)
        return match
      }
    })
  } catch (error) {
    console.error('处理公式内容出错:', error)
    return content
  }
}


// 组件挂载时获取数据
onMounted(async () => {
  await Promise.all([
    fetchSubjects(),
    fetchQuestionTypes(),
    fetchAnswerTypes()
  ])
  fetchQuestions()
})
</script>

<template>
  <div class="question-container">
    <!-- 搜索和筛选区域 -->
    <el-card class="filter-container" shadow="never">
      <el-form :inline="true" class="filter-form">
        <el-form-item label="关键词">
          <el-input
            v-model="searchKeyword"
            placeholder="试题标题关键词"
            clearable
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        
        <el-form-item style="width: 15%;" label="学科">
          <el-select v-model="selectedSubject" placeholder="选择学科" clearable @change="handleSubjectChange">
            <el-option
              v-for="subject in subjectList"
              :key="subject.id"
              :label="subject.name"
              :value="subject.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item style="width: 15%;" label="题型">
          <el-select v-model="selectedType" placeholder="选择题型" clearable>
            <el-option
              v-for="type in questionTypeList"
              :key="type.id"
              :label="type.name"
              :value="type.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 试题列表 -->
    <el-card class="list-container" shadow="never">
      <template #header>
        <div class="card-header">
          <span>试题列表</span>
          <div>
            <el-button 
              v-if="userInfo.roleName !== ROLES.TEACHER" 
              type="primary" 
              @click="handleAddQuestion"
            >新增试题</el-button>
          </div>
        </div>
      </template>
      
      <el-table
        v-loading="loading"
        :data="questionList"
        border
        style="width: 100%"
      >
        <el-table-column label="序号" width="80">
          <template #default="{$index}">
            <span>{{ (pagination.currentPage - 1) * pagination.pageSize + $index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="试题标题" min-width="200" show-overflow-tooltip>
          <template #default="{row}">
            <div v-html="renderMathFormula(row.name)" class="question-title-cell"></div>
          </template>
        </el-table-column>
        <el-table-column prop="subjectName" label="所属学科" width="120" />
        <el-table-column label="题型" width="120">
          <template #default="{row}">
            <span>{{ formatQuestionType(row.questionTypeId) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="难度" width="100">
          <template #default="{row}">
            <el-tag
              :color="formatDifficulty(row.hardLevel).color"
              effect="plain"
              style="color: white"
            >
              {{ formatDifficulty(row.hardLevel).label }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="试题内容" min-width="300">
          <template #default="{row}">
            <div class="question-content-preview" v-if="row.questionContent" v-html="renderMathFormula(formatQuestionContent(row.questionContent))"></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{row}">
            <el-button link type="primary" size="small" @click="handleViewQuestion(row)">查看</el-button>
            <el-button 
              v-if="canEditSpecificQuestion(row)" 
              link 
              type="primary" 
              size="small" 
              @click="handleEditQuestion(row)"
            >编辑</el-button>
            <el-button 
              v-if="canDeleteSpecificQuestion(row)" 
              link 
              type="danger" 
              size="small" 
              @click="handleDeleteQuestion(row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 试题表单对话框 -->
    <el-dialog
      :title="isEdit ? '编辑试题' : '新增试题'"
      v-model="dialogVisible"
      width="80%"
      destroy-on-close
    >
      <question-form
        :question-data="currentQuestion"
        :is-edit="isEdit"
        @submit-success="handleFormSuccess"
        @cancel="handleFormCancel"
      />
    </el-dialog>
    
    <!-- 试题详情对话框 -->
    <el-dialog
      v-model="questionDetailVisible"
      title="试题详情"
      width="60%"
      destroy-on-close
      @closed="closeQuestionDetail"
      custom-class="question-detail-dialog"
    >
      <div v-if="questionDetail" class="question-detail-container">
        <div class="question-detail-header">
          <h2 class="question-title" v-html="questionDetail.formattedName"></h2>
          <div class="question-meta">
            <span class="difficulty-tag" :style="{backgroundColor: questionDetail.difficulty.color}">
              {{ questionDetail.difficulty.label }}
            </span>
            <span class="subject-tag">{{ questionDetail.subjectName }}</span>
          </div>
        </div>
        
        <div class="question-detail-content">
          <div class="detail-item">
            <div class="detail-label">试题内容</div>
            <div class="detail-value" v-html="questionDetail.formattedContent"></div>
          </div>
          
          <div class="detail-item">
            <div class="detail-label">所属大题</div>
            <div class="detail-value">{{ questionDetail.bigQuestionName || '未分配' }}</div>
          </div>

          <div class="detail-item">
            <div class="detail-label">题型</div>
            <div class="detail-value">{{ questionDetail.questionTypeName }}</div>
          </div>
          
          <div class="detail-item">
            <div class="detail-label">答案类型</div>
            <div class="detail-value">{{ questionDetail.answerTypeName }}</div>
          </div>
          
          <div class="detail-item">
            <div class="detail-label">知识点</div>
            <div class="detail-value">{{ questionDetail.knowledgePointName || '未分配' }}</div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.question-container {
  padding: 20px 0;
}

.filter-container {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.list-container {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.question-content-preview {
  max-width: 100%;
  white-space: normal;
  word-break: break-word;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.question-title-cell {
  display: inline-block;
  max-width: 100%;
}

.question-title-cell .katex {
  font-size: 1em;
}

/* 试题详情样式 */
.question-detail-container {
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.question-detail-header {
  margin-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
  padding-bottom: 15px;
}

.question-title {
  margin: 0 0 15px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.question-meta {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 8px;
}

.difficulty-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  color: white;
}

.subject-tag {
  padding: 2px 8px;
  background-color: #ecf5ff;
  color: #409eff;
  border-radius: 4px;
  font-size: 12px;
}

.question-detail-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.detail-label {
  font-weight: 600;
  color: #606266;
  font-size: 14px;
}

.detail-value {
  color: #303133;
  line-height: 1.6;
  font-size: 14px;
  background-color: #f8f9fa;
  padding: 8px 12px;
  border-radius: 4px;
}
</style>

<style>
/* 全局样式：试题详情对话框 */
.question-detail-dialog .el-message-box {
  max-width: 600px;
  width: 90%;
  border-radius: 8px;
  overflow: hidden;
}

.question-detail-dialog .el-message-box__header {
  background-color: #f5f7fa;
  padding: 15px 20px;
}

.question-detail-dialog .el-message-box__title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.question-detail-dialog .el-message-box__headerbtn {
  top: 15px;
  right: 20px;
}

.question-detail-dialog .el-message-box__content {
  padding: 0;
}

.question-detail-dialog .el-message-box__btns {
  padding: 10px 20px 15px;
  text-align: right;
}

.question-detail-dialog .el-button--primary {
  background-color: #409eff;
  border-color: #409eff;
  padding: 8px 20px;
  border-radius: 4px;
}

/* 全局数学公式样式 */
.katex-display {
  margin: 0.5em 0;
  overflow-x: auto;
  overflow-y: hidden;
  padding: 2px;
}

.katex {
  font-size: 1.1em;
}
</style>
